package ckw.network;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import ckw.gui.MainWindowC;

import core.messages.Info;



public class Listen implements Runnable {
	private ConnectionC cm;
	private ServerSocket SSocket;
	private Queue2 queue2;
	private StanC stanC = null;

	public Listen(ConnectionC c, ServerSocket SSocket, Queue2 queue2, StanC stanC){
		cm = c;
		this.SSocket = SSocket;
		this.queue2 = queue2;
		this.stanC = stanC;
	}
	
	public void run(){
		boolean timeout = false;
		stanC.setNasluchiwanie(true);

        while(!timeout){
            Socket CSocket = null;
            try {
				CSocket = SSocket.accept();
				Komisja dobraKomisja = null;
				
				for(Komisja k: cm.komisje)
					if(("/"+k.getIp()).equals(CSocket.getInetAddress().toString())){
						dobraKomisja = k;
					}
				
				if(dobraKomisja!=null){
					
					ObjectOutputStream oos = null;
					ObjectInputStream ois = null;
					
					try{
						oos = new ObjectOutputStream(CSocket.getOutputStream());
						ois = new ObjectInputStream(CSocket.getInputStream());
					} catch(Exception e){
						e.printStackTrace();
					}
					if(ois!=null){
						System.out.println("Polaczono nowa komisje i wyslano powitanie");	
						System.out.println(CSocket.getInetAddress().toString());
						dobraKomisja.setOis(ois);
						dobraKomisja.setOos(oos);
						dobraKomisja.setSocket(CSocket);
						dobraKomisja.setThread(new Thread(new ReceiverC(dobraKomisja, cm, queue2, stanC)));
						dobraKomisja.getThread().start();
						MainWindowC.aktualizujKomisje();
				        Info msg = new Info(stanC.getNr(), 0);
						cm.sendDown(dobraKomisja, msg);
	
					}
				}
				
			} catch (Exception e) {
				e.printStackTrace();
				timeout = true;
			}
		}
        stanC.setNasluchiwanie(false);
        System.out.println("Minal czas oczekiwania");  
	}
}
